package cn.ycxy.lbl.repairs.security;

import cn.ycxy.lbl.common.exception.enums.ResponseEnum;
import cn.ycxy.lbl.common.restful.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author BaoL
 * @Date 2023/3/12 12:31
 * @Description 处理权限不足
 * @Since version-1.0
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    private static final ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //在这里返回一个包含着错误信息的对象数据
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(R.setResult(ResponseEnum.FORBIDDEN)));
        httpServletResponse.flushBuffer();
    }
}
